<?php

namespace App\Kuafu\User\Model;

use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\Feishu\Model\FsUserModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Scope\ShopScope;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Schema\Builder;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Base implements JWTSubject
{
    use Notifiable, KfUid, KfSoftDeletes;

    protected $connection = 'mysql';
    protected $table      = 'users';
    protected $hidden     = ['password', 'salt'];
    protected $fillable = ['brandId', 'username', 'mobile', 'feishuUserId', 'password', 'salt', 'status', 'inductionAt', 'isDeleted', 'photo', 'healthCardPhoto', 'healthCardPhotoDate', 'createdAt', 'updatedAt'];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims(): array
    {
        return [];
    }

    public static function setUserInfoById($userId, $data)
    {
        $user = User::where(['id' => $userId])->first();
        $user->update($data);

        return $user;
    }

    public static function getUserInfoById($userId, $field)
    {
        return User::query()->where('id', '=', $userId)->select($field)->first();
    }

    public static function getUserByField($field, $value)
    {
        return User::where([$field => $value])->first();
    }

    /**
     * 根据column查询指定数据
     * @param $column
     * @param $value
     * @param $arr
     * @return mixed
     */
    public static function getUserValue($column, $value, $arr = [])
    {
        return User::where($column, $value)
                   ->when(!empty($arr), function ($query) use ($arr) {
                       $query->select($arr);
                   })
                   ->first();
    }


    /**
     * @param $name
     * @param $status
     * @param $pageSize
     * @param $pageNum
     * @param int $brandId
     * @param string $mobile
     * @param int $roleId
     * @param int $shopId
     * @return LengthAwarePaginator
     */
    public static function getUserDataPage(
        $name,
        $status,
        $pageSize,
        $pageNum,
        int $brandId = 0,
        string $mobile = '',
        int $roleId = 0,
        int $shopId = 0
    ): LengthAwarePaginator {
        return self::query()
                   ->withGlobalScope("shopScope", new ShopScope(
                           function($builder){
//                               $userId = UserRoleMapping::query()
//                                   ->whereIn("shopId", ShopScope::getShopIdsArr())
//                                   ->get()
//                                   ->groupBy("userId")
//                                   ->map(function(Collection $v, $k){
//                                       if($v->pluck("shopId")->unique()->count() == count(ShopScope::getShopIdsArr())){
//                                           return $k;
//                                       }
//                                       return 0;
//                                   })->filter()->toArray();

                               $userId = UserRoleMapping::query()
                                   ->whereIn("shopId", ShopScope::getShopIdsArr())
                                   ->get()
                                   ->pluck("userId")
                                   ->toArray();

                               $builder->whereIn('id', $userId);
                           }
                        ))
                   ->where('brandId', $brandId)
                   ->when($name, function ($query) use ($name) {
                            $query->where('username', 'like', "%{$name}%");
                        })
                   ->when($mobile, function ($query) use ($mobile) {
                            $query->where('mobile', '=', $mobile);
                        })
                        ->when($status !== null, function ($query) use ($status) {
                            $query->where('status', (int)$status);
                        })
                   ->when($roleId > 0, function ($query) use ($roleId) {
                            $query->whereHas('userRoleMappingRel', function ($query) use ($roleId) {
                                if ($roleId > 0) {
                                    $query->where('roleId', '=', $roleId);
//                                          ->where('type', '=', RoleCodeEnum::ROLE_WEB_TYPE);
                                }
                            });
                        })
                   ->where('isDeleted', '=', 0)
                   ->orderBy('status')
                   ->orderBy('id')
                   ->paginate($pageSize, ['id', 'username', 'mobile', 'status', 'createdAt'], $pageName = 'page',
                            $pageNum);
    }

    public static function getValueById($id, $value)
    {
        return self::query()->where(['id' => $id])->value($value);
    }

    /**
     * 活动详情，根据用户id查询创建人
     * @param $userId
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getUserNameByUid($userId)
    {
        return User::query()->where('id', '=', $userId)->get();
    }

    public function userRoleMappingRel(): HasMany
    {
        return $this->hasMany(UserRoleMapping::class, 'userId', 'id');
    }

    //用户角色表关联
    public function roleRel(): HasManyThrough
    {
        return $this->hasManyThrough(
            Role::class,
            UserRoleMapping::class,
            'userId',
            'id',
            'id',
            'roleId');
    }

    //用户角色枢纽表与商家表关联
    public function shopRel()
    {
        return $this->hasManyThrough(
            Shop::class,
            UserRoleMapping::class,
            'userId',
            'id',
            'id',
            'shopId');
    }

    //用户角色枢纽表与商家表关联
    public function addressRel()
    {
        return $this->hasManyThrough(
            Shop::class,
            UserRoleMapping::class,
            'userId',
            'id',
            'id',
            'shopId');
    }

    //获取用户创建人
    public function createdUserRel()
    {
        return $this->hasOne(
            User::class,
            'id',
            'createdByUid',
        );
    }

    /**
     * 根据用户id列表查询用户信息
     * @param $userIds
     * @param $field
     */
    public static function getUserInfoByIds($userIds, array $fields = ['*'])
    {
        return self::query()
                   ->whereIn('id', $userIds)
                    ->with(['fsUserRel'])
                   ->select($fields)
                   ->get();
    }

    public static function getUserInfoByMobiles(array $mobiles)
    {
        return self::query()
            ->whereIn('mobile', $mobiles)
            ->get();
    }


    /**
     * @return HasMany
     */
    public function fsUserRel(): HasMany
    {
        return $this->hasMany(FsUserModel::class, "mobile", "mobile");
    }


    /**
     * @return HasOne
     */
    public function userIdCardRel(): HasOne
    {
        return $this->hasOne(UserIdCardDetailModel::class, "userId", "id");
    }

}
